# -*- coding:utf-8 -*-
import functools

from flask import session, current_app, g

from info import constants
from info.models import User, News, Category


def do_index_class(idx):
    """模板过滤器"""
    if idx == 1:
        return "first"
    elif idx == 2:
        return "second"
    elif idx == 3:
        return "third"
    return ""


def get_user_info(f):
    """获取用户登录信息"""

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 查询用户登录信息
        userId = session.get("userId")
        user = None
        if userId:
            try:
                user = User.query.get(userId)
            except Exception as e:
                current_app.logger.error(e)
        g.user = user
        return f(*args, **kwargs)

    return wrapper


def get_hits_info(f):
    """获取右侧点击排行数据"""

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 右侧点击排行数据
        newsList = []
        try:
            newsList = News.query.filter(News.status == 0).order_by(News.clicks.desc()).limit(
                constants.CLICK_RANK_MAX_NEWS)
        except Exception as e:
            current_app.logger.error(e)
        g.newsBasicList = [news.to_dict() for news in newsList]
        return f(*args, **kwargs)

    return wrapper


def get_category_info(f):
    """获取新闻类型数据"""

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        categories = []
        try:
            categories = Category.query.order_by(Category.create_time).all()
        except Exception as e:
            current_app.logger.error(e)
        g.categoryList = [category.to_dict() for category in categories]
        return f(*args, **kwargs)

    return wrapper
